package newkfp;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import pojos.Treausry;

@ManagedBean(name = "moneyController")
@SessionScoped
public class MoneyController implements Serializable {
Loger loger;
private DataModel Treasury_items = null;
private Date toDate=new Date(),fromDate=new Date();
 private PaginationHelper paginationTreasurys;
@EJB
    private newkfp.LogFacade logFacade;
    private Treausry current;
    private DataModel items = null;
    @EJB
    private newkfp.TreausryFacade ejbFacade;
    @EJB
    private newkfp.CustomerFacade customerFacade;
    @EJB
    private newkfp.ExporterFacade exporterFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String genDesc;
    private String money;
    private Date date;
    private String customerName;
    private String exporterName;
    private boolean moneyType;
    private Double total;

    public MoneyController() {
    }

    public Double getTotal() {
         
        total = getFacade().findSum(fromDate,toDate);
        System.out.println("//Total: " + total);
        return total;
    }

    public void setTotal(Double total) {
        this.total = total;
    }

    public Treausry getSelected() {
        if (current == null) {
            current = new Treausry();
            selectedItemIndex = -1;
        }
        return current;
    }

    private TreausryFacade getFacade() {
        return ejbFacade;
    }

    private CustomerFacade getCustomerFacade() {
        return customerFacade;
    }

    private ExporterFacade getExporterFacade() {
        return exporterFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Treausry) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Treausry();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("MoneyCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Treausry) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("MoneyUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Treausry) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("MoneyDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Treausry.class)
    public static class MoneyControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            MoneyController controller = (MoneyController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "moneyController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Treausry) {
                Treausry o = (Treausry) object;
                return getStringKey(o.getTreasuryId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + MoneyController.class.getName());
            }
        }
    }

    ////////////A7med Kotb///////////////////
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getGenDesc() {
        return genDesc;
    }

    public void setGenDesc(String genDesc) {
        this.genDesc = genDesc;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public String saveData() {
         loger=new Loger(getLogFacade());
        current = new Treausry();
        current.setGeneralDescription(genDesc);
        current.setActionDate(date);
        if (moneyType == true) {
            current.setMoneyAmount(Double.parseDouble("+" + money));
             String s="تم اضافة  مبلغ  ";
           
            loger.LogerString(s+money, 0);
        } else {
            current.setMoneyAmount(Double.parseDouble("-" + money));
             String s="تم سحب  مبلغ  ";
           
            loger.LogerString(s+money, 0);
        }

        Employee emp = new Employee(1);
        current.setEmployeeId(emp);
        getFacade().create(current);
        clearSession();
        return "treasuryhome";
    }

    public List<String> autocomplete(String inputValue) {
        try {
            System.out.println("//Search Text: " + inputValue);
            String test=new String(inputValue.getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("/////test: "+test);
            List<Customer> objList = getCustomerFacade().searchCustomers(inputValue);
            List<String> customersNames = new ArrayList<String>();
            for (Iterator<Customer> it = objList.iterator(); it.hasNext();) {
                Customer cust = it.next();
                customersNames.add(cust.getCustomerName());
            }
            return customersNames;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MoneyController.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public List<String> autocomplete1(String inputValue) {
        System.out.println("//Search Text: " + inputValue);
        List<Exporter> objList = getExporterFacade().searchExporters(inputValue);
        List<String> exporterNames = new ArrayList<String>();
        for (Iterator<Exporter> it = objList.iterator(); it.hasNext();) {
            Exporter cust = it.next();
            exporterNames.add(cust.getExporterName());
        }
        return exporterNames;
    }

    public String getExporterName() {
        return exporterName;
    }

    public void setExporterName(String exporterName) {
        this.exporterName = exporterName;
    }

    public String saveCust() {
        loger=new Loger(getLogFacade());
        current = new Treausry();
        
        
        current.setActionDate(date);
        Customer cust = getCustomerFacade().findByName(customerName);
        current.setCustomerId(cust);
        
        Double customerBalance = cust.getBalance();

        if (moneyType == true) { //masroofat
            current.setMoneyAmount(Double.parseDouble("-" + money));
            if (customerBalance < 0) {//3aleeh
                customerBalance = customerBalance - Double.parseDouble(money);
            } else {//laho
                customerBalance = customerBalance - Double.parseDouble(money);
            }
            String s="تم استرجاع مبلغ  ";
            String ss="الي العميل ";
            loger.LogerString(s+money+ss+" "+cust.getCustomerName(), 0);
            String t="استرجع للعميل : ";
            current.setGeneralDescription(t+cust.getCustomerName());
        } else {//madfoo3at
            current.setMoneyAmount(Double.parseDouble("+" + money));
            if (customerBalance < 0) {//3aleeh
                customerBalance = customerBalance + Double.parseDouble(money);
            } else {//laho
                customerBalance = customerBalance + Double.parseDouble(money);
            }
             String s="تم تحصيل مبلغ  ";
            String ss="من العميل ";
            loger.LogerString(s+money+ss+" "+cust.getCustomerName(), 0);
            String t="دفعه من العميل : ";
            current.setGeneralDescription(t+cust.getCustomerName());
        }
        Employee emp = new Employee(1);
        current.setEmployeeId(emp);
        cust.setBalance(customerBalance);
        getCustomerFacade().edit(cust);
        getFacade().create(current);
        clearSession();
        return "treasuryhome";
    }

    public String saveExp() {
        loger=new Loger(getLogFacade());
        current = new Treausry();
        current.setActionDate(date);

        Exporter exp = getExporterFacade().findByExpoterName(exporterName);
        current.setExporterId(exp);
        Double exporterBalance = exp.getBalance();
        if (moneyType == true) {//madfoo3at
            current.setMoneyAmount(Double.parseDouble("+" + money));
            if (exporterBalance < 0) {//3aleeh
                exporterBalance = exporterBalance + Double.parseDouble(money);
            } else {//laho
                exporterBalance = exporterBalance + Double.parseDouble(money);
            }
             String s="تم ارسال مبلغ  ";
            String ss="الي المورد ";
            loger.LogerString(s+money+ss+" "+exp.getExporterName(), 0);
     String t="استرد من المورد : ";

            current.setGeneralDescription(t+exp.getExporterName());

        } else {//masroofat
            current.setMoneyAmount(Double.parseDouble("-" + money));
            if (exporterBalance < 0) {//3aleeh
                exporterBalance = exporterBalance - Double.parseDouble(money);
            } else {//laho
                exporterBalance = exporterBalance - Double.parseDouble(money);
            }
             String s="تم اضافة مبلغ  ";
            String ss="الي المورد ";
            loger.LogerString(s+money+ss+" "+exp.getExporterName(), 0);
                       String t="دفعه الي المورد : ";

            current.setGeneralDescription(t+exp.getExporterName());
        }
        Employee emp = new Employee(1);
        current.setEmployeeId(emp);
        exp.setBalance(exporterBalance);
        getExporterFacade().edit(exp);
        getFacade().create(current);
clearSession();
        return "treasuryhome";
    }

    public boolean isMoneyType() {
        return moneyType;
    }

    public void setMoneyType(boolean moneyType) {
        this.moneyType = moneyType;
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }

   public void  clearSession(){
    Map m=  FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    m.remove("exporterController");   
    
m.remove("employeeController"); 
m.remove("customerController"); 
m.remove("countryController"); 
m.remove("billInformationController"); 
m.remove("inventoryStoreController"); 
//m.remove("moneyController"); 
m.remove("billConfirmController"); 
m.remove("billExporterInformationController"); 
m.remove("logController"); 
m.remove("itemController"); 

    }

    public Date getFromDate() {
        return fromDate;
    }

    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    public Date getToDate() {
        return toDate;
    }

    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }
   
   public String prepareTreasury() {
        recreateModel();
        return "treasuryhome";
    }
   public DataModel getTreasury_items() {
        paginationTreasurys=null;
        Treasury_items=null;
            Treasury_items = getTreausryPagination().createPageDataModel();
            System.out.println("Bill Items: "+Treasury_items.getRowCount());
        return Treasury_items;
    }

   public PaginationHelper getTreausryPagination() {
        if (paginationTreasurys == null) {
            paginationTreasurys = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    Calendar calendar = Calendar.getInstance();
                    if (toDate != null) {
                        calendar.setTime(toDate);
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    return new ListDataModel(getFacade().getTreasuryAtPeriod( fromDate, calendar.getTime()));
                }
            };
        }
        return paginationTreasurys;
    }


}
